﻿using System.Web;
using System.IO;
using System.ServiceModel.Channels;
using System.Xml;
using System.Xml.Serialization;

namespace GlimpseWcf.Core
{

    public class CookieMessageHeader : MessageHeader
    {
        private readonly HttpContextBase _context;
        private const string GlimpseWcf = "GlimpseWcf";
        private const string WcfHeader = "WcfHeader";

        public CookieMessageHeader(HttpContextBase context)
        {
            _context = context;
        }

        protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
        {
            var cookieDto = new CookieCollectionDto(_context.Request.Cookies);
            var serializer = new XmlSerializer(typeof (CookieCollectionDto));
            var textWriter = new StringWriter();
            serializer.Serialize(textWriter, cookieDto);
            textWriter.Close();

            writer.WriteElementString(Name, Namespace, textWriter.ToString());
        }

        public static CookieCollectionDto ReadHeader(Message request)
        {
            var headerPosition = request.Headers.FindHeader("WcfHeader", "GlimpseWcf");
            if (headerPosition == -1)
                return null;
            
            string text = request.Headers.GetHeader<XmlNode[]>(headerPosition)[0].InnerText;
            var deserializer = new XmlSerializer(typeof (CookieCollectionDto));
            var textReader = new StringReader(text);
            var cookies = (CookieCollectionDto)deserializer.Deserialize(textReader);
            textReader.Close();

            return cookies;
        }

        public override string Name
        {
            get { return WcfHeader; }
        }

        public override string Namespace
        {
            get { return GlimpseWcf; }
        }
    }
}


